package com.da.landlord;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.googlecode.cswish.annotation.Rest;
import com.googlecode.cswish.model.PageInfo;
import com.googlecode.cswish.oosearch.Condition;
import com.googlecode.cswish.oosearch.QLInfo;
import com.googlecode.cswish.struts.spring.GenericService;
import com.ra.landlord.FeeRuleCfg;
import com.ra.landlord.FeeRuleCfgCalc;
import com.ra.landlord.FeeRuleCfgDesc;
import com.ra.landlord.FeeRuleCfgDescService;
import com.ra.landlord.LandlordUserService;

/**
 * 房间抄表费用项配置
 * @author Peter Z
 *
 */
@Service
public class DaRoomMeterItemService {
	

	@Resource
	private FeeRuleCfgDescService feeRuleCfgDescService;
	
	@Resource
	private LandlordUserService landlordUserService;
	
	@Resource
	private GenericService genericService;
	
	@Resource
	private DaMeterService daMeterService;
	
	
	/**
	 * 获取非公摊的仪表信息
	 * @return
	 */
	@Rest(type = "search")
	public List<FeeRuleCfgDesc> showMeterFeeRuleCfg(){
		DaRoom room  = new DaRoom();
		PageInfo<DaRoom> page = genericService.searchByModel(room, Condition.DEFAULT, true, false);
		List<DaRoom> lsRoom = page.getData();
		
		Set<FeeRuleCfg> cfgs = new TreeSet<>(new Comparator<FeeRuleCfg>() {
			@Override
			public int compare(FeeRuleCfg o1, FeeRuleCfg o2) {
				return o1.getId()-o2.getId();
			}
		});
		
		for (DaRoom daRoom : lsRoom) {
			List<DaFeeRule> feerules = daRoom.getFeeRules();
			if( feerules == null )continue;
			for (DaFeeRule daFeeRule : feerules) {
				FeeRuleCfg cfg =  daFeeRule.getFeeRuleCfg();
				cfgs.add(cfg);
			}
		}
		List<FeeRuleCfgDesc> result = new ArrayList<FeeRuleCfgDesc>();
		if( cfgs.size() != 0 ){
			Iterator<FeeRuleCfg > iterator =  cfgs.iterator();
			while( iterator.hasNext() ){
				FeeRuleCfg cfg = iterator.next();
				FeeRuleCfgDesc desc = cfg.getFeeRuleCfgDesc();
				if( desc != null){
					FeeRuleCfgDesc newDesc = new FeeRuleCfgDesc();
					newDesc.setName("非公摊-"+desc.getName());
					newDesc.setId(desc.getId());
					result.add(newDesc);
					//名字相同，但价格有可能不同
				}
			}
		}
		return result;
	}
	
	@Rest(type="search")
	public Map<String,List<DaFeeRule>> searchMetersForSuite(Integer suiteId) {
		Map<String,List<DaFeeRule>> result = new HashMap<String,List<DaFeeRule>>();
		List<FeeRuleCfg> feeRuleCfgs = daMeterService.showMeterFeeRuleCfgForSuite(suiteId);
		DaSuite suite = genericService.load(DaSuite.class, suiteId);
		
		for (FeeRuleCfg feeRuleCfg : feeRuleCfgs) {
			List<DaFeeRule> matchedFeeRules = new ArrayList<DaFeeRule>();
			Integer feeRuleCfgDescId = feeRuleCfg.getFeeRuleCfgDesc().getId();
			// 设置本次抄表，上一次抄表和上上一次抄表
			Calendar today = Calendar.getInstance();
			Calendar checkDate = Calendar.getInstance();
			FeeRuleCfgCalc feeRuleCfgCalc = new FeeRuleCfgCalc();
			DaFeeRule matchedFeeRule = null;
			for (DaFeeRule feeRule : suite.getFeeRules()) {
				// 从suite的feerule集合中找到当前分类的那条feerule
				if (feeRule.getFeeRuleCfg() != null && feeRule.getFeeRuleCfg().getFeeRuleCfgDesc() != null
						&& feeRule.getFeeRuleCfg().getFeeRuleCfgDesc().getId().equals(feeRuleCfgDescId)) {
					matchedFeeRule = feeRule;
					break;
				}
			}
			if (matchedFeeRule != null) {
				List<DaMeter> meters = matchedFeeRule.getMeters();
				feeRuleCfgCalc = matchedFeeRule.getFeeRuleCfg().getFeeRuleCfgCalc();
				if (meters != null && meters.size() > 0) {
					matchedFeeRule.setLastMeter(meters.get(0));
					if (meters.size() > 1) {
						matchedFeeRule.setLastLastMeter(meters.get(1));
					}
				}
				// 仅仅是为了保证前台可以拿到feeRuleId
				DaMeter currentMeter = new DaMeter();
				matchedFeeRule.setCurrentMeter(currentMeter);
				currentMeter.setFeeRule(matchedFeeRule);
				matchedFeeRules.add(matchedFeeRule);
			}
			for (DaRoom room : suite.getRooms()) {
				matchedFeeRule = null;
				for (DaFeeRule feeRule : room.getFeeRules()) {
					// 从suite的feerule集合中找到当前分类的那条feerule
					if (feeRule.getFeeRuleCfg() != null && feeRule.getFeeRuleCfg().getFeeRuleCfgDesc() != null
							&& feeRule.getFeeRuleCfg().getFeeRuleCfgDesc().getId().equals(feeRuleCfgDescId)) {
						matchedFeeRule = feeRule;
						break;
					}
				}
				if (matchedFeeRule == null) {
					continue;
				}
				List<DaMeter> meters = matchedFeeRule.getMeters();
				feeRuleCfgCalc = matchedFeeRule.getFeeRuleCfg().getFeeRuleCfgCalc();
				if (meters != null && meters.size() > 0) {
					matchedFeeRule.setLastMeter(meters.get(0));
					if (meters.size() > 1) {
						matchedFeeRule.setLastLastMeter(meters.get(1));
					}
				}
				DaMeter currentMeter = new DaMeter();
				currentMeter.setFeeRule(matchedFeeRule);
				matchedFeeRule.setCurrentMeter(currentMeter);
				matchedFeeRules.add(matchedFeeRule);
			}
			if (matchedFeeRules.size()>0) {
				result.put(matchedFeeRules.get(0).getFeeRuleCfg().getFeeRuleCfgDesc().getName(), matchedFeeRules);
			}
		}
		return result;
	}

	/**
	 * 根据仪表查询房间
	 * @param buildingId
	 * @param feeRuleCfgId
	 * @return
	 */
	@Rest(type = "search")
	public List<DaSuite> searchSuiteWithMeter(Integer feeRuleCfgDescId) {
		
		/*DaSuite example = new DaSuite();
		List<DaFeeRule> feeRuleList = new ArrayList<DaFeeRule>();
		List<DaRoom> roomList = new ArrayList<DaRoom>();
		DaFeeRule feeRuleExample = new DaFeeRule();
		FeeRuleCfg feeRuleCfgExample = new FeeRuleCfg();
		FeeRuleCfgDesc feeRuleCfgDescExample = new FeeRuleCfgDesc();
		DaRoom roomExample = new DaRoom();
		
		example.setFeeRules(feeRuleList);
		example.getFeeRules().add(feeRuleExample);
		feeRuleCfgExample.setFeeRuleCfgDesc(feeRuleCfgDescExample);
		feeRuleCfgDescExample.setId(feeRuleCfgDescId);
		feeRuleExample.setFeeRuleCfg(feeRuleCfgExample);
		roomExample.setFeeRules(feeRuleList);
		roomList.add(roomExample);
		//example.setRooms(roomList);
		Condition cond = Condition.DEFAULT;
		cond.setLogicFlag(Condition.LOGIC_OR);
		@SuppressWarnings("unused")
		List<DaSuite> data = genericService.searchByModel(example, cond).getData();*/
		
		QLInfo qlInfo = new QLInfo("select a from DaSuite a where  exists (select feeRule.id from DaFeeRule feeRule where feeRule.suite=a  and feeRule.feeRuleCfg.feeRuleCfgDesc.id=?) or EXISTS (select room.id from DaRoom room where room.suite=a and exists(select feeRule.id from DaFeeRule feeRule where feeRule.room=room and feeRule.feeRuleCfg.feeRuleCfgDesc.id=?) ) ", false, feeRuleCfgDescId,feeRuleCfgDescId);
		qlInfo.setCompiledSort("a.name");
		qlInfo.setDir("asc");
		@SuppressWarnings("unchecked")
		List<DaSuite> data = (List<DaSuite>) genericService.searchByQl(qlInfo).getData();
		//设置本次抄表，上一次抄表和上上一次抄表
		Calendar today = Calendar.getInstance();
		Calendar checkDate =  Calendar.getInstance();
		FeeRuleCfgCalc feeRuleCfgCalc =  new FeeRuleCfgCalc();
		for(DaSuite suite : data){
			DaFeeRule matchedFeeRule = null;
			for(DaFeeRule feeRule : suite.getFeeRules()){
				//从suite的feerule集合中找到当前分类的那条feerule
				if(feeRule.getFeeRuleCfg()!=null&&feeRule.getFeeRuleCfg().getFeeRuleCfgDesc()!=null&&feeRule.getFeeRuleCfg().getFeeRuleCfgDesc().getId().equals(feeRuleCfgDescId)){
					matchedFeeRule = feeRule;
					break;
				}
			}
			if (matchedFeeRule != null) {
				List<DaMeter> meters = matchedFeeRule.getMeters();
				feeRuleCfgCalc = matchedFeeRule.getFeeRuleCfg().getFeeRuleCfgCalc();
				if (meters != null && meters.size() > 0) {
					suite.setLastMeter(meters.get(0));
					if (meters.size() > 1) {
						suite.setLastLastMeter(meters.get(1));
					}
				}
				//仅仅是为了保证前台可以拿到feeRuleId
				DaMeter currentMeter = new DaMeter();
				currentMeter.setFeeRule(matchedFeeRule);
				suite.setCurrentMeter(currentMeter);
			}
			
			for(DaRoom room : suite.getRooms()) {
				matchedFeeRule = null;
				for(DaFeeRule feeRule : room.getFeeRules()){
					//从suite的feerule集合中找到当前分类的那条feerule
					if(feeRule.getFeeRuleCfg()!=null&&feeRule.getFeeRuleCfg().getFeeRuleCfgDesc()!=null&&feeRule.getFeeRuleCfg().getFeeRuleCfgDesc().getId().equals(feeRuleCfgDescId)){
						matchedFeeRule = feeRule;
						break;
					}
				}
				if(matchedFeeRule==null) {
					continue;
				}
				List<DaMeter> meters = matchedFeeRule.getMeters();
				feeRuleCfgCalc = matchedFeeRule.getFeeRuleCfg().getFeeRuleCfgCalc();
				if(meters != null && meters.size()>0){
					room.setLastMeter(meters.get(0));
					if (meters.size() > 1) {
						room.setLastLastMeter(meters.get(1));
					}
				}
				//仅仅是为了保证前台可以拿到feeRuleId
				DaMeter currentMeter = new DaMeter();
				currentMeter.setFeeRule(matchedFeeRule);
				room.setCurrentMeter(currentMeter);
			}
		}
		
		return data;
		
		
		
		
		
	/*	// 已抄表: room.feeRule.meter
		DaRoom model = new DaRoom();
		LandlordUser landlordUser = landlordUserService.getLoginUser();
		model.setLandlordUser(landlordUser.getOwnerUser());
		
		// 表类型
		// ModelUtil.setProperty(model, "feeRule.feeRuleCfg.feeRuleCfgDesc.id", meterTypeId);
		PageInfo<DaRoom> pageInfo = genericService.searchAll(model);
		int today = Calendar.getInstance().get(Calendar.DAY_OF_YEAR);
		List<DaRoom> daRooms = new ArrayList<DaRoom>();
		for (DaRoom daRoom : pageInfo.getData()) {
			DaFeeRule matchedFeeRule = null;
			for (DaFeeRule feeRule : daRoom.getFeeRules()) {
				if (feeRule != null && feeRule.getFeeRuleCfg() != null && feeRule.getFeeRuleCfg().getFeeRuleCfgDesc() != null) {
					if (feeRuleCfgId.equals(feeRule.getFeeRuleCfg().getFeeRuleCfgDesc().getId())) {
						matchedFeeRule = feeRule;
						break;
					}
				}
			}
			if (matchedFeeRule != null) {
				List<DaMeter> lstMeter = matchedFeeRule.getMeters();
				
				if (lstMeter == null || lstMeter.size() == 0) {
					//初始化表刻度
					DaMeter initMeter = new DaMeter();
					initMeter.setCount(BigDecimal.valueOf(0));
					initMeter.setFeeRule(matchedFeeRule);
					initMeter.setCheckTime(null);
					daRoom.setLastMeter(initMeter);
					daRooms.add(daRoom);
				}else if(lstMeter.size() >= 1){
					DaMeter meter = matchedFeeRule.getMeter(0);
					Calendar checkTime = Calendar.getInstance();
					checkTime.setTime(meter.getCheckTime());
					// 判断抄表是否为本次收费周期
					boolean isCurrentMonthMeter = false;
					FeeRuleCfg feeRuleCfg = matchedFeeRule.getFeeRuleCfg();
					if (feeRuleCfg != null) {
						FeeRuleCfgCalc feeRuleCfgCalc = feeRuleCfg.getFeeRuleCfgCalc();
						if (feeRuleCfgCalc.getRentCycleType() == 0) {//按月
							isCurrentMonthMeter = today - checkTime.get(Calendar.DAY_OF_YEAR) < feeRuleCfgCalc.getRentCycle()* 30;
						}
					}
					if (isCurrentMonthMeter) {
						daRoom.setCurrentMeter(meter);
						if (lstMeter.size() >= 2) {
							daRoom.setLastMeter(matchedFeeRule.getMeter(1));
							if (lstMeter.size() >= 3) {
								daRoom.setLastLastMeter(matchedFeeRule.getMeter(2));
							}
						}else{
							DaMeter initMeter = new DaMeter();
							initMeter.setCount(BigDecimal.valueOf(0));
							initMeter.setFeeRule(matchedFeeRule);
							initMeter.setCheckTime(null);
							daRoom.setLastMeter(initMeter);
						}
						
						daRooms.add(daRoom);
					} else {
						daRoom.setLastMeter(meter);
						if (lstMeter.size() >= 2) {
							daRoom.setLastLastMeter(matchedFeeRule.getMeter(1));
						}
						daRooms.add(daRoom);
					}
				}
			}
		}
		return daRooms;
		*/
	}
	
	
	
}
